package com.tmall.testgen.transfer.server;

import java.io.InputStream;
import java.io.OutputStream;

import com.tmall.testgen.common.bo.interact.back.TransferCarFromClient;
import com.tmall.testgen.common.bo.interact.back.TransferCarFromServer;
import com.tmall.testgen.common.bo.interact.back.syn.AttatchJvmResult;
import com.tmall.testgen.common.bo.interact.back.syn.GetJvmListResult;
import com.tmall.testgen.common.socket.ReceiveObjectHandler;
import com.tmall.testgen.common.socket.TransferHandler;
import com.tmall.testgen.common.util.VMUtil;

/**
 * @author haojia
 * @date 2014-07-04
 */
public class TransferServerReceiveObjectHandler  implements  ReceiveObjectHandler {

    public OutputStream out; 

    public TransferServerReceiveObjectHandler(OutputStream out){
        this.out=out;
    }
	@Override
	public void handleReceiveObj(Object receive) {
	    
	    if(!(receive instanceof TransferCarFromClient )){
            System.out.println(receive.getClass().getName());
            return;
        }
        
        TransferCarFromClient car=(TransferCarFromClient) receive;
        
        switch(car.getType()){
            case TransferCarFromClient.TYPE_GET_JVM_LIST:
                //连接成功后马上返回本机虚拟机地址
            try {
                TransferHandler.writeObject(out,new TransferCarFromServer(new GetJvmListResult().setJvmList(VMUtil.getLocalVMs())));
            } catch (Exception e1) {
                e1.printStackTrace();
            }
                break;
            case TransferCarFromClient.TYPE_CONNECT_TO_ATTATCH:
                String transferJarPath=this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
                String agentJarPath=transferJarPath.replaceAll("transfer.jar", "test_gen_agent.jar");
                
            try {
                TransferHandler.writeObject(out,new TransferCarFromServer(new AttatchJvmResult()));
            } catch (Exception e1) {
                e1.printStackTrace();
            }
                
            try {
                VMUtil.attatch((String) car.getData(), agentJarPath);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        
		
	}
	
//	public static void main(String[] args) {
//	    TransferServerReceiveObjectHandler a=new TransferServerReceiveObjectHandler(null);
//	    System.out.println(a.getClass().getResource("/").getPath());
//    }

}
